//
//  UIViewController+KSNavigator.m
//  BasketBallLeagues
//
//  Created by kenshin on 4/23/17.
//  Copyright © 2017 kenshin. All rights reserved.
//

#import "UIViewController+KSNavigator.h"
#import "AppDelegate.h"

@implementation UIViewController (KSNavigator)

+ (void)ks_pushViewController:(UIViewController *)viewController
                     animated:(BOOL)animated
{
    [[self ks_rootNavigationController] pushViewController:viewController
                                                  animated:animated];
}

+ (void)ks_pushViewControllerClass:(Class)vcClass animated:(BOOL)animated
{
    if (![vcClass isSubclassOfClass:[UIViewController class]]) {
        return;
    }
    UIViewController *vc = [self viewControllerForClass:vcClass];
    if (vc) {
        [[self ks_rootNavigationController] popToViewController:vc
                                                       animated:animated];
        return;
    }
    [self ks_pushViewController:[vcClass new]
                       animated:animated];
}

+ (void)ks_presentViewController:(UIViewController *)viewControllerToPresent
                        animated:(BOOL)flag
                      completion:(void (^)(void))completion
{
    [[self ks_rootNavigationController] presentViewController:viewControllerToPresent
                                                     animated:flag
                                                   completion:completion];
}

+ (UINavigationController *)ks_rootNavigationController
{
    return [(AppDelegate *)[[UIApplication sharedApplication] delegate] rootNavigationController];
}

+ (UIViewController *)viewControllerForClass:(Class)class
{
    for (UIViewController *vc in [self ks_rootNavigationController].viewControllers) {
        if ([vc isKindOfClass:class]) {
            return vc;
        }
    }
    return nil;
}

@end
